package factory_pattern.simple_factory.connection_impl;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import java.net.URI;
import java.util.concurrent.CountDownLatch;

// WebSocket客户端端点（JSR-356标准）
@ClientEndpoint
public class WebSocketConnection implements NetworkConnection {
    private final String url;
    private Session session;
    private final CountDownLatch connectLatch = new CountDownLatch(1); // 同步等待连接

    public WebSocketConnection(String url) {
        this.url = url;
    }

    @Override
    public boolean connect() {
        try {
            // 建立WebSocket连接（同步等待）
            ContainerProvider.getWebSocketContainer()
                    .connectToServer(this, new URI(url));
            connectLatch.await(); // 等待连接完成
            System.out.printf("[WebSocket] 连接成功：%s%n", url);
            return true;
        } catch (Exception e) {
            System.out.printf("[WebSocket] 连接失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendData(byte[] data) {
        if (session == null || !session.isOpen()) {
            System.out.println("[WebSocket] 连接未建立，无法发送");
            return false;
        }
        try {
            session.getBasicRemote().sendBinary(java.nio.ByteBuffer.wrap(data));
            System.out.printf("[WebSocket] 发送成功：%d 字节%n", data.length);
            return true;
        } catch (Exception e) {
            System.out.printf("[WebSocket] 发送失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public void close() {
        if (session != null && session.isOpen()) {
            try {
                session.close();
                System.out.printf("[WebSocket] 连接关闭：%s%n", url);
            } catch (Exception e) {
                System.out.printf("[WebSocket] 关闭失败：%s%n", e.getMessage());
            } finally {
                session = null;
            }
        }
    }

    // WebSocket连接打开时触发（回调方法）
    @javax.websocket.OnOpen
    public void onOpen(Session session) {
        this.session = session;
        connectLatch.countDown(); // 释放等待
    }
}